package com.wink.admin.utils;


import cn.hutool.core.util.ObjectUtil;
import com.wink.admin.common.response.ApiResponse;
import com.wink.admin.common.response.ResultCode;

/**
 * @author donaldhan
 * 接口返回工具类
 */
public class ResponseUtils {
    private static ThreadLocal<ApiResponse> responseThreadLocal = new ThreadLocal<>();

    public static ApiResponse ok() {
        ApiResponse apiResponse = new ApiResponse();
        responseThreadLocal.set(apiResponse);

        return apiResponse;
    }

    public static ApiResponse ok(Object data) {
        ApiResponse apiResponse = new ApiResponse();
        if (ObjectUtil.isEmpty(data)) {
            apiResponse.setMessage("找不到数据");
        } else {
            apiResponse.setData(data);
        }
        responseThreadLocal.set(apiResponse);

        return apiResponse;
    }


    public static ApiResponse setResult(ResultCode resultCode) {
        ApiResponse apiResponse = getApiResponse(resultCode.getCode(), resultCode.getMsg());
        responseThreadLocal.set(apiResponse);
        return apiResponse;
    }

    public static ApiResponse setResult(ResultCode resultCode, Object data) {
        ApiResponse apiResponse = getApiResponse(resultCode.getCode(), resultCode.getMsg());
        apiResponse.setData(data);
        responseThreadLocal.set(apiResponse);
        return apiResponse;
    }

    public static ApiResponse setResult(Integer code, String message, Object data) {
        ApiResponse apiResponse = getApiResponse(code, message);
        apiResponse.setData(data);
        if (ObjectUtil.isNotEmpty(data)) {
            apiResponse.setData(data);
        }
        responseThreadLocal.set(apiResponse);

        return apiResponse;
    }


    public static ApiResponse setResult(Integer code, String message) {
        ApiResponse apiResponse = getApiResponse(code, message);
        apiResponse.setData(null);
        responseThreadLocal.set(apiResponse);

        return apiResponse;
    }

    private static ApiResponse getApiResponse(Integer code, String message) {
        ApiResponse apiResponse = new ApiResponse();
        apiResponse.setCode(code);
        apiResponse.setMessage(message);
        return apiResponse;
    }


    public static ApiResponse getResult() {
        ApiResponse apiResponse = responseThreadLocal.get();
        ResponseUtils.remove();
        return apiResponse;
    }

    public static void remove() {
        responseThreadLocal.remove();
    }
}
